#include "dominion.h"
#include "dominion_helpers.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#include <time.h>

int main (int argc, char** argv) {
  struct gameState G;

  int k[10];
  int count[27];
  int i;
  int rando;
  int play_count;
  int j;
  int rand_card;
  int temp;
  int err;


  srand(time(NULL));

  count[0] = 1;
  count[1] = 1;
  count[2] = 1;
  count[3] = 1;
  count[4] = 1;
  count[5] = 1;
  count[6] = 1;
  //rand set of kingdom cards from 7-26
  rando = rand()%27;

  for(i=0; i<10; i++){
      while(count[rando] == 1){
        rando = rand()%27;
      }
      k[i] = rando;
      printf("Kingdom card %d is %d\n", i, k[i]);
      count[rando] = 1;
  }


  //rand number of players

    play_count = 2 + rand()%2;


  printf("Number of players are %d\n", play_count);

  err = initializeGame(play_count, k, atoi(argv[1]), &G);
  if (-1 == err){
    printf("Failed to intialize game\n");
    exit(EXIT_FAILURE);
  }


  printf("Game Started\n");



  int money = 0;
  i=0;

  while (!isGameOver(&G)) {
    money = 0;
    for(i=0; i<numHandCards(&G);i++){
      printf("Cards in hand: %d\n", handCard(i, &G));
    }


  printf("Round %d\n", j);
  j++;



  //Action Phase
  for(i=0; i<numHandCards(&G);i++){
    rand_card = rand() % numHandCards(&G);
    if(playCard(rand_card, -1, -1, -1, &G) != -1){
      printf("Played %d card.", rand_card);
      break;
    }
  }


  //Buy Phase

  for (i = 0; i < numHandCards(&G); i++) {
    if (handCard(i, &G) == copper){
      money++;
    }
    else if (handCard(i, &G) == silver){
      money += 2;
    }

    else if (handCard(i, &G) == gold){
      money += 3;
    }

  }

  printf("%d money in hand\n", money);

  if(money>=3){
    rand_card = rand()%10;
    while(supplyCount(rand_card, &G) == 0 || getCost(k[rand_card]) > money){
      rand_card = rand()%10;
      }
      printf("Buying %d Card\n", k[rand_card]);

      buyCard(rand_card, &G);
    }




      printf("%d: endTurn\n", whoseTurn(&G));

      endTurn(&G);
  } // end of While

  printf("Finished game.\n");

  for(i=0;i<play_count;i++){
    printf("Player %d: %d\n", i, scoreFor(i, &G));
  }

  return 0;
}
